package william.list;

/**
 * @author ZhangShenao
 * @date 2024/1/12
 * @description <a href="https://leetcode.cn/problems/merge-two-sorted-lists/description/">...</a>
 */
public class Leetcode21_合并两个有序链表 {
    private class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    /**
     * 借助哑头节点实现
     * 时间复杂度O(N) 两个链表各遍历一遍
     * 空间复杂度O(1)
     */
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        //边界条件校验
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }

        //借助一个哑头节点
        ListNode dummy = new ListNode();
        ListNode cur = dummy;

        //同时遍历两个链表,将较小的节点追加到新链表末尾,并向后移动
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                cur.next = list1;
                list1 = list1.next;
            } else {
                cur.next = list2;
                list2 = list2.next;
            }
            cur = cur.next;
        }

        //处理还剩余一个链表的情况
        if (list1 != null) {
            cur.next = list1;
        }
        if (list2 != null) {
            cur.next = list2;
        }


        //返回头节点
        return dummy.next;
    }

}
